import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image, Picker, Swiper, SwiperItem } from '@tarojs/components'
import {AtList, AtListItem, AtToast, AtButton, AtFloatLayout, AtSwipeAction, AtIcon, AtInput, AtTag, AtActionSheet, AtActionSheetItem, AtImagePicker, AtModal, AtModalHeader, AtModalContent, AtModalAction, AtCurtain} from 'taro-ui'
import './editCase.scss'
import reactMixin  from 'react-mixin'
import myJs from './editCaseJs.js'
import app from '../../../main'
import upload_image from '../../../img/icon_jia.png'
import icon_delete from '../../../img/icon_delete.png'

export default class EditCase extends Component {
    constructor () { 
        super(...arguments); 
        this.state = this.getData(); 
    }
    config = {
        navigationBarTitleText: '病历详情'
    }

    componentWillMount () {
        this.init();
    }

    componentDidShow(){
        this.getTags();
        this.getCase_detail();
        this.allCourse();
    }

    init() {
        this.setState({
            isOpen1: true,
            isOpen2: true,
            isOpen3: true,
            isOpen4: false,
            isShare: false,
            text: '',
            isShowRefuseNote: false,
            isOpenImage: false,
            image: ''
        });
        this.getBaseTemplate();
        this.getCase_detail();
    }
    showImage(image, images) {
        var urls = [];
        for (var i = 0; i < images.length; i++) {
            urls.push(images[i].url);
        }
        app.prviewImage(image, urls);
    }
    closeImage() { 
        this.setState({
            isOpenImage: false
        })
    }
    closeRefuseNote() {
        this.setState({
            isShowRefuseNote: false
        }); 
    }

    //调用api接口 get 某病历所打的标签
    getTags(){
        let me = this;
        let data = {
            id:me.state.case_detail.id
        }
        app.get('web/caselabel/case_labels',data,function(res){
            me.setState({
                getTags:res.data.result
            })
        })
    }

    handleClose() {
        this.setState({
            isOpen4: false,
        });
    }

    swipeClick(data, v) {
        if(v.text == '编辑') {
            this.gotoEdit('../createCourse/createCourse?id=' + data.id + '&type=' + data.type);
        } else if(v.text == '删除') {
            this.deleteCourse(data.id);
        }
    }

    addCourse() {
        this.setState({
            isOpen4: true,
        });
    }

    toAddCourse(type, case_template_id) {
        this.setState({
            isOpen4: false,
        });
        app.navigateTo("../createCourse/createCourse?case_id=" + this.state.case_detail.id + "&type=" + type + '&course_name=' + type + '&case_template_id=' + case_template_id);
    }

    openPanel(name) {
        this.state[name] = !this.state[name];
        this.setState({
            name: this.state[name]
        });
    }

    onChange = e => {
        this.setState({
            sexChecked: this.state.sexRang[e.detail.value]
        })
    }

    onMarryChange = e => {
        this.setState({
            marryChecked: this.state.marryRang[e.detail.value]
        })
    }

    onDateChange = e => {
        this.setState({
            dateChecked: e.detail.value
        })
    }

    onCityChange = e => {
        this.setState({
            cityChecked: this.state.cityRang[0][e.detail.value[0]] + this.state.cityRang[1][e.detail.value[1]]
        })
    }

    showToast(text) {
        this.setState({
            message: text,
            isOpened: true
        });
    }

    toastClose() {
        this.setState({
            isOpened: false
        });
    }

    gotoEdit(url) {
        var me = this;
        if(!me.state.editable && me.state.case_detail.type == '病例') {
            console.log('不可编辑');
            return;
        }
        app.navigateTo(url);
    }
    gotoCourse(url, id) {
        var me = this;
        console.log('current', app.current);
        console.log('case_detail', me.state.case_detail);
        if(!me.state.editable) {
            // if ((app.current.type == '医生' && app.current.id != me.state.case_detail.doctor_id)
            //     || (app.current.type == '专员' && app.current.id != me.state.case_detail.promoter_id)
            // ) {
            //     app.navigateTo('../courseDetail/courseDetail?id='+id);
            // }
            app.navigateTo('../courseDetail/courseDetail?id='+id);
            return;
        }
        app.navigateTo(url);
    }
    taghandleClick(){
        let id = this.state.case_detail.id;
        app.navigateTo('../../patientlables/pages/medical/medical?id='+id)
    }
    toastClick(){
        app.navigateTo('../medicalStatus/medicalStatus')
    }
    statusClick(){
        let id = this.state.case_detail.id;
        app.navigateTo('../medicalStatus/medicalStatus?id='+id);
    }
    toCooperations() {
        console.log('state', this.state);
        var id = this.state.case_detail.id;
        console.log('id', id);
        app.navigateTo('../../patientlables/pages/cooperations/cooperations?id='+this.state.case_detail.id);
    }
    openShare(v) {
        this.setState({
            isShare: v
        });
    }
    suifang(){
        var me = this;
        let pid = this.state.case_detail.patient_id;
        let name = this.state.case_detail.patient_name;
        let phone = this.state.case_detail.phone
        if(pid > 0){
            app.get('web/myself/is_has_order_with_doctor', {doctor_id: app.current.id, patient_id: pid}, function(res) {
                var result = res.data.result;
                if (result.is_has_order) {
                    app.navigateTo('/pages/chat/pages/Chat/Chat?type='+result.type+'&relate_id='+result.order_id+'&receiver_id='+pid)
                } else {
                    app.post('web/flow_order/submitOrder', {patient_id: pid, flow_plan_id: 0}, function(res) {
                        if (res.data.status == 200) {
                            var relate_id = res.data.result.id;
                            app.navigateTo('/pages/chat/pages/Chat/Chat?type=随访'+'&receiver_id='+pid+'&relate_id='+relate_id)
                        }
                    })
                }
            })
        }else{
            app.navigateTo('/pages/flow/pages/tianjiahuanzhe/tianjiahuanzhe'+`?name=${name}&phone=${phone}`)
        }
    }
    gotosuifangdialog(){
        var me = this;
        app.post('web/flow_order/submitOrder', {patient_id: me.state.patient_id, flow_plan_id: 0}, function(res) {
            if (res.data.status == 200) {
                var relate_id = res.data.result.id;
                app.navigateTo('../../../chat/pages/Chat/Chat?type=随访'+'&receiver_id='+me.state.patient_id+'&relate_id='+relate_id)
            }
        })
    }
    toshareDongTai() {
        let me = this
        app.redirectTo('/pages/dynamic/pages/fabudongtai/fabudongtai'+`?blurl=${this.state.case_detail.id}`)
    }
    // 微信转发
    onShareAppMessage(res) {
        return {
          title: '病历详情',
          imageUrl: app.getPath('img/share_case.png'),
          path: 'pages/doctorpages/caseDetail/caseDetail?id=' + this.state.case_detail.id
        }
    }

    render () {
        return (
            <View className='editCase'>
                <AtCurtain
                    isOpened={this.state.isOpenImage}
                    onClose={this.closeImage.bind(this)}
                >
                    <Image style='width:100%;' src={app.getPath(this.state.image)} />
                </AtCurtain>
                <AtToast onClose={this.toastClose} hasMask={true} isOpened={this.state.isOpened} text={this.state.message} icon="alert-circle" onClick={this.toastClick.bind(this)} ></AtToast>
                <AtFloatLayout isOpened={this.state.isOpen4} title="选择病程类型" onClose={this.handleClose.bind(this)}>
                    <AtList hasBorder={false}>  
                        {
                            this.state.case_detail.course_form.map((item) => {
                                return <AtListItem title={item.name} arrow='right' onClick={this.toAddCourse.bind(this, item.name, item.case_template_id)}/>
                            })
                        }
                    </AtList>
                </AtFloatLayout>
                <View className={this.state.isShowRefuseNote ? 'refuse_note' : 'hidden'}>
                    <AtIcon value='close-circle' size='26' color='#666666' className='icon_close' onClick={this.closeRefuseNote.bind(this)}></AtIcon>
                    {
                        this.state.case_detail.status == '初审待修改'
                        &&
                        <View className='refuse'>初审不通过原因：{this.state.case_detail.chushen_refuse_reason}</View>
                    }
                    {
                        this.state.case_detail.status == '终审待修改'
                        &&
                        <View className='refuse'>终审不通过原因：{this.state.case_detail.zhongshen_refuse_reason}</View>
                    }
                </View>
                <View className="btns-view">
                    {
                        this.state.case_detail.type == '病例' && this.state.editable == true
                        ?
                        <AtButton onClick={this.submit.bind(this)} type='primary' size='small' circle={true}>提交</AtButton>
                        :
                        <AtButton onClick={this.submit.bind(this)} type='primary' size='small' circle={true} disabled={true}>提交</AtButton>
                    }
                    <AtButton onClick={this.toCooperations.bind(this)} type='primary' size='small' circle={true}>协作</AtButton>
                    <AtButton type='primary' size='small' circle={true} onClick={this.suifang.bind(this)}>随访</AtButton>
                    <AtButton type='primary' size='small' circle={true} onClick={this.openShare.bind(this, true)}>分享</AtButton>
                    <AtButton onClick={this.delete.bind(this)} type='primary' size='small' circle={true}>删除</AtButton>
                </View>
                {/*患者信息  */}
                <AtList>
                    {
                        (this.state.case_detail.doctor_id == app.current.id)
                        ?
                        <AtListItem onClick={this.gotoEdit.bind(this, '../editPatientInfo/editPatientInfo?id='+this.state.case_detail.id)} hasBorder={false} title={this.state.case_detail.patient_name + ' ' + this.state.case_detail.code} note={this.state.case_detail.gender+' '+this.state.case_detail.age+'岁'+' '+ this.state.case_detail.city + ' ' + this.state.case_detail.phone} arrow='right' thumb={app.imageUri+'images/default-user.png'}/>
                        :
                        <AtListItem onClick={this.gotoEdit.bind(this, '../editPatientInfo/editPatientInfo?id='+this.state.case_detail.id)} hasBorder={false} title={this.state.case_detail.code} note={this.state.case_detail.gender} arrow='right' thumb={app.imageUri+'images/default-user.png'}/>
                    }
                    
                </AtList>

                <View className="panel">
                    <View className="header">
                        <Text className="txt">病历标签</Text>

                        {
                            (this.state.case_detail.status != null && this.state.case_detail.status != "null" && this.state.case_detail.status != '')
                            &&
                            <View className="btns">
                                <AtButton type='secondary' size='small' className="btn" onClick={this.statusClick.bind(this)}>{this.state.case_detail.status}</AtButton>
                            </View>
                        }
                    </View>

                    <View className="tags-view">
                        {
                            this.state.getTags.map((item) => {
                                return (
                                    <View>
                                       {item.name == null ? none : <AtTag className="tag" type='primary' size='normal'>{item.name}</AtTag>} 
                                    </View>
                                )
                            })
                        }
                        <AtTag className="tag" type='primary' size='normal' onClick={this.taghandleClick.bind(this)}>+ 添加标签</AtTag>
                    </View>
                </View>

                {
                    this.state.template.map((item) => {
                        return item.type == '矩阵填空题' ? 
                        (
                            <View className='panel'>
                                <View className="header">
                                    <Text className="txt">{item.label}</Text>
                                    <View className="btns">
                                        <AtButton type='secondary' size='small' className="btn" onClick={this.gotoEdit.bind(this, "../editCaseInfo/editCaseInfo?id="+this.state.case_detail.id)}>编辑</AtButton>
                                        <AtButton onClick={this.openPanel.bind(this, 'isOpen1')} type='secondary' size='small' className="btn">{this.state.isOpen1? '收起': '展开'}</AtButton>
                                    </View>
                                </View>
                                <View className={this.state.isOpen1 ? '': 'hidden'}>
                                {
                                    item.items.map((one) => {
                                        return <View className='base_item'>
                                                <View className='base_label'>{one.label}</View>
                                                <View className='base_value'>{this.state.case_detail[one.name]}</View>
                                            </View>
                                    })
                                }
                                </View>
                            </View>
                        ) : 
                        (item.type == '眼科检查' ? 
                        (
                            <View className='panel'>
                                <View className="header">
                                    <Text className="txt">{item.label}</Text>

                                    <View className="btns">
                                        <AtButton type='secondary' size='small' className="btn" onClick={this.gotoEdit.bind(this, "../editInspect/editInspect?id="+this.state.case_detail.id)}>编辑</AtButton>
                                        <AtButton onClick={this.openPanel.bind(this, 'isOpen3')} type='secondary' size='small' className="btn">{this.state.isOpen3? '收起': '展开'}</AtButton>
                                    </View>
                                </View>
                                <View className={this.state.isOpen3 ? '': 'hidden'}>
                                    <View className='eye'>
                                        <View className='eye1'>项目</View>
                                        <View className='eye2'>右眼</View>
                                        <View className='eye3'>左眼</View>
                                    </View>
                                    {
                                        this.state.inspect_list.map((one) => {
                                            return (one.v1 != '' || one.v2 != '')
                                            &&
                                            <View className='eye_item'>
                                                    <View className='eye_value1'>{one.label}</View>
                                                    <View className='eye_value2'>{one.v2}</View>
                                                    <View className='eye_value3'>{one.v1}</View>
                                            </View>
                                        })
                                    }
                                </View>
                            </View>
                        ) : 
                        (item.type == '上传图片' ? 
                        (
                            <View className='panel'>
                                <View className="header">
                                    <Text className="txt">{item.label}</Text>
                                </View>
                                <View className='editCaseImage'>
                                    <AtModal isOpened={this.state.imgModal}>
                                        <AtModalHeader>请输入照片名称</AtModalHeader>
                                        <AtModalContent>
                                            <AtInput type='text' value={this.state.text} onChange={this.handleChange.bind(this, 'text')}/>
                                        </AtModalContent>
                                        <AtModalAction>
                                            <Button onClick={this.closeModal.bind(this)}>取消</Button> 
                                            <Button onClick={this.comfirmModal.bind(this)}>确定</Button>
                                        </AtModalAction>
                                    </AtModal>
                                    <View className="subject">
                                        {
                                            this.state.case_detail.physical_images.map((k) => {
                                                return <View className='item_box'>
                                                            <View className='item_img'><Image src={k.url} style='width:200rpx;height:200rpx;' mode='widthFix' onClick={this.showImage.bind(this, k.url, this.state.case_detail.physical_images)}></Image></View>
                                                            <View className='item_txt'>{k.text}</View>
                                                            <Image src={icon_delete} onClick={this.deleteImage.bind(this, k.url)} className='img_delete' style='width:50rpx;height:50rpx;'></Image>
                                                        </View>
                                            })
                                        }
                                        <View className='upload_box'>
                                            <View className='icon_upload' onClick={this.imageChange}>
                                                <Image src={upload_image} style='width:100rpx;height:100rpx;'></Image>
                                            </View>
                                        </View>
                                    </View>
                                </View>
                            </View>
                        ) : (null)))
                    })
                }

                <View className='panel mg_bottom'>
                    <View className="header">
                        <Text className="txt">病程</Text>

                        <View className="btns">
                            <AtButton onClick={this.openPanel.bind(this, 'isOpen2')} type='secondary' size='small' className="btn">{this.state.isOpen2? '收起': '展开'}</AtButton>
                        </View>
                    </View>

                    <View className={this.state.isOpen2 ? '': 'hidden'}>
                        <AtList>
                            {
                                this.state.case_courses.map((item)=>{
                                    return (
                                        <AtSwipeAction onClick={this.swipeClick.bind(this, item)} options={[
                                            {
                                                text: '删除',
                                                style: {
                                                backgroundColor: '#FF4949'
                                                }
                                            }
                                            ]}>
                                            <AtListItem onClick={this.gotoCourse.bind(this, '../createCourse/createCourse?id=' + item.id + '&type=' + item.type + '&case_id=' + this.state.case_detail.id + '&course_name=' + item.name + '&case_template_id=' + item.case_template_id, item.id)} title={item.name} extraText={item.visit_at} />
                                        </AtSwipeAction>
                                    )
                                })
                            }
                        </AtList>
                        <View className={this.state.editable? 'header': 'hidden'} onClick={this.addCourse.bind(this)}>
                            <View>
                                <AtIcon value='add-circle' size='20' color='#4bd863'></AtIcon>
                                <Text className="txt">添加病程</Text>
                            </View>
                        </View>
                    </View>
                </View>
                <View className='f-btn'>
                    <AtIcon onClick={this.navigateBack.bind(this, '../medicalhomepage/medicalhomepage')} value='home' size='30' color='#fff'></AtIcon>
                </View>

                {/* 分享菜单 */}
                <AtActionSheet isOpened={this.state.isShare} cancelText='取消' title='' onClose={this.openShare.bind(this, false)} onCancel={this.openShare.bind(this, false)}>
                    <AtActionSheetItem>
                        <Button open-type='share' plain className='btn_share_weixin'>分享至微信</Button>
                    </AtActionSheetItem>
                    <AtActionSheetItem onClick={this.toshareDongTai.bind(this)}>
                        分享至动态
                    </AtActionSheetItem>
                </AtActionSheet>

                <View className='empty'></View>
            </View>
        );
    }
}

reactMixin.onClass(EditCase, myJs);
